/**
 * 
 */
package demo.dcs.util;

import java.util.ArrayList;
import java.util.List;

import net.sf.cglib.beans.BeanCopier;



public class XdcsBeanUtils {
	    
	
	/**
	 * @param source	
	 * @param target	
	 */
	public static <T, V> void copy(T source, V target) {
		if(source == null || target == null)return;
		
		BeanCopier beanCopier = BeanCopier.create(source.getClass(), target.getClass(), false);
		
		beanCopier.copy(source, target, null);
	}
	
	/**
	 * 
	 * @param source	
	 * @param clazz		
	 * @return
	 */
	public static <T, V> V convert(T source, Class<V> clazz) {
		if(source == null)return null;
		
		BeanCopier beanCopier = BeanCopier.create(source.getClass(), clazz, false);
		
		try {
			V targetObj = clazz.newInstance();
			
			beanCopier.copy(source, targetObj, null);
			
			return targetObj;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 
	 * @param sourceList	
	 * @param clazz			
	 * @return
	 */
	public static <T, V> List<V> convertList(List<T> sourceList, Class<V> clazz) {
		if(sourceList == null || sourceList.isEmpty())
			return null;
		
		List<V> targetList = new ArrayList<V>();
		
		BeanCopier beanCopier = null;
		
		for(T sourceObj : sourceList){
			if(beanCopier == null) {
				beanCopier = BeanCopier.create(sourceObj.getClass(), clazz, false);
			}
			
			try {
				V targetObj = clazz.newInstance();
				
				beanCopier.copy(sourceObj, targetObj, null);
				
				targetList.add(targetObj);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return targetList;
	}
	
	public static boolean isImplInterface(Class c, String szInterface) {
		Class[] face = c.getInterfaces();
		for (int i = 0, j = face.length; i < j; i++) {
			if (face[i].getName().equals(szInterface)) {
				return true;
			} else {
				Class[] face1 = face[i].getInterfaces();
				for (int x = 0; x < face1.length; x++) {
					if (face1[x].getName().equals(szInterface)) {
						return true;
					} else if (isImplInterface(face1[x], szInterface)) {
						return true;
					}
				}
			}
		}
		if (null != c.getSuperclass()) {
			return isImplInterface(c.getSuperclass(), szInterface);
		}
		return false;
	}

    public static boolean isClassExist(String className){
        try {
            Class.forName(className);
        }catch (Throwable e){
            return false;
        }
        return true;
    }
}
